import { Navigate, useLocation } from 'react-router'
import type { ReactNode } from 'react'
import { useAuth } from '@/hooks/useAuth'
import { Spin } from 'antd'

interface AuthGuardProps {
  children: ReactNode
  requiredRoles?: string[] // 可选：基于角色的权限控制
}

const Index = ({ children, requiredRoles }: AuthGuardProps) => {
  const { user, loading } = useAuth()
  const location = useLocation()

  if (loading) {
    return <Spin fullscreen />
  }

  // 没有用户信息，跳转到登录页
  if (!user) {
    return <Navigate to='/login' state={{ from: location }} replace />
  }

  // 检查角色权限
  if (requiredRoles && !requiredRoles.includes(user.role)) {
    return <Navigate to='/unauthorized' replace />
  }

  return <>{children}</>
}

export default Index
